/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.util;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThreadContext {

    static Logger log = LoggerFactory.getLogger(ThreadContext.class);
    private static ThreadLocal<ThreadContext> threadLocal = new ThreadLocal<ThreadContext>();
    private Map<String, Object> data = new HashMap<String, Object>();

    public Object get(Class<? extends Object> c) {
        return get(c.getName());
    }

    public Object get(String s) {
        Object obj = data.get(s);
        if (obj == null) {
            throw new IllegalStateException("Object not found: " + s);
        }
        return obj;
    }

    public static ThreadContext get() {
        ThreadContext ctx = threadLocal.get();
        if (ctx == null) {
            throw new IllegalStateException("Current thread not bound");
        }
        return ctx;
    }

    public void put(Class<? extends Object> c, Object obj) {
        put(c.getName(), obj);
    }

    public void put(String s, Object obj) {
        data.put(s, obj);
    }

    public void bindThread() {
        ThreadContext ctx = threadLocal.get();
        if (ctx != null) {
            log.warn("{} already bound", Thread.currentThread());
        }
        threadLocal.set(this);
    }

    public static void unbindThread() {
        threadLocal.set(null);
    }

    public void execute(Runnable r) {
        try {
            bindThread();
            r.run();
        } finally {
            unbindThread();
        }
    }

}
